package com.itcm.studyMongodb.spring;

import com.itcm.studyMongodb.Person;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class PersonDao {

    @Autowired
    private MongoTemplate mongoTemplate;

    // 增
    public Person savePerson(Person person) {
        Person person1 = this.mongoTemplate.save(person);
        return person1;
    }

    // 查
    public List<Person> queryPersonListByAge(int age) {
        Query query = Query.query(Criteria.where("age").is(age));
        List<Person> personList = this.mongoTemplate.find(query, Person.class);
        return personList;
    }

    // 分页查询
    public List<Person> queryPagePersonList(Integer page, Integer rows) {
        Query query = new Query().limit(rows).skip((page - 1) * rows);
        return this.mongoTemplate.find(query, Person.class);
    }

    // 改
    public UpdateResult update(Person person) {
        Query query = Query.query(Criteria.where("id").is(person.getId()));
        Update update = Update.update("age", person.getAge());
        return this.mongoTemplate.updateFirst(query, update, Person.class);
    }

    // 删
    public DeleteResult deleteById(String id) {
        Query query = Query.query(Criteria.where("id").is(id));
        return this.mongoTemplate.remove(query, Person.class);
    }
}
